/**
 * Created by zhouli on 18/3/9
 * Email li.zhou@huilianyi.com
 * 法人实体的创建与更新
 * 选择账套列表
 * 选择上级法人
 * 上传二维码图片
 * 提交表单创建法人
 *
 * 有点注意：多语言的校验单独处理，没有在表单校验
 */
import React from 'react';
import {Button, Form, Input, Col, Row, Switch, message, Icon, Select, Modal} from 'antd';
import {connect} from 'react-redux';

import config from 'config';
import 'styles/enterprise-manage/legal-person/new-legal-person.scss';
import LPService from 'containers/enterprise-manage/legal-person/legal-person.service';
import Selector from 'components/selector';
import {LanguageInput} from 'components/index';
import {messages, getLanguageName} from 'share/common';

import {ImageUpload} from 'components/index';
import debounce from 'lodash.debounce';

const FormItem = Form.Item;
const Option = Select.Option;

class NewLegalPerson extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleTips: false,
      payErrTips: {
        subMsg: "",
        tip: ""
      },
      loading: false,
      //上级法人下拉单
      parentLegalEntityList: [],
      //选择账套下拉单
      sob: {
        url: `${config.baseUrl}/api/setOfBooks/by/tenant`,
        label: record => `${record.setOfBooksName}`,
        key: 'id',
      },
      //账套
      //默认的法人实体
      legalPerson: {
        accountBank: "",//开户行
        address: "",//地址
        companyName: "",//名称

        cardNumber: "",//银行卡号
        enable: true,//状态
        i18n: {},//包含开户行，地址，名称

        setOfBooksId: null,//账套
        telephone: "",//电话
        taxpayerNumber: "",//税号

        parentLegalEntityId: "",//上级法人
        mainLanguage: "zh_cn",//开票显示语言
        mainLanguageName: messages('enterprise-manage.key99'/*简体中文*/),//简体中文
        i118entityName: null,//对应的是companyName多语言
        i118accountBank: null,
        i118address: null,
        legalEntityAttachmentDTOs: [{
          attachmentId: 10,
          filePath: "",
          name: "",
          i18n: {name: []},
        }],
      },
    };
    this.handleUploadImageChange = debounce(this.handleUploadImageChange, 300)
  }

  componentDidMount() {
    if (!this.props.params.legalPersonOID) {
      //直接获取法人列表无需过滤
      this.getParentLegalEntity();
    } else {
      this.getLegalPersonDetail();
    }
  }

  //获取上级法人，需要过滤当前法人
  getParentLegalEntity = (filterId) => {
    LPService.getParentLegalEntity()
      .then(res => {
        let data = res.data;
        if (filterId) {
          let filterList = data.filter(item => item.id !== filterId);
          this.setState({
            parentLegalEntityList: filterList
          })
        } else {
          this.setState({
            parentLegalEntityList: data
          })
        }
      })
  };

  getLegalPersonDetail = () => {
    LPService.getLegalPersonDetail(this.props.params.legalPersonOID)
      .then((res) => {
        let data = res.data;
        if (data.legalEntityAttachmentDTOs) {
          if (data.legalEntityAttachmentDTOs.length < 5) {
            data.legalEntityAttachmentDTOs.push({
              attachmentId: 10,
              filePath: "",
              name: "",
              i18n: {name: []},
            })
          }
        } else {
          data.legalEntityAttachmentDTOs = [{
            attachmentId: 10,
            filePath: "",
            name: "",
            i18n: {name: []},
          }];
        }
        if (data.companyName) {
          if (!data.i18n) {
            data.i18n = {entityName: [{language: "zh_cn", value: data.companyName}]};
          }
          if (!data.i18n.entityName) {
            data.i18n.entityName = [{language: "zh_cn", value: data.companyName}];
          }
        }
        //需要过滤当前法人
        this.getParentLegalEntity(data.id);
        //前端设置一下语言
        data.mainLanguageName = getLanguageName(data.mainLanguage, this.props.languageList);
        this.setState({
          legalPerson: data,
        })
      });
  };

  //校验多语言
  validateI18n = (legalPerson) => {
    if (legalPerson.companyName === "" ||
      legalPerson.companyName === undefined ||
      legalPerson.companyName === null) {
      // 请填写法人实体名称
      message.error(messages('enterprise-manage.key100'/*请填写法人实体名称*/));
      return false;
    }
    if (legalPerson.accountBank === "" ||
      legalPerson.accountBank === undefined ||
      legalPerson.accountBank === null) {
      // 请填写开户行
      message.error(messages('enterprise-manage.key101'/*请填写开户行*/));
      return false;
    }
    if (legalPerson.address === "" ||
      legalPerson.address === undefined ||
      legalPerson.address === null) {
      // 请填写地址
      message.error(messages('enterprise-manage.key102'/*请填写地址*/));
      return false;
    }
    return true;
  };

  handleSave = (e) => {
    const {legalPerson} = this.state;
    e.preventDefault();
    let _legalPerson = legalPerson;
    if (this.validateI18n(_legalPerson)) {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          let err = false;
          if (_legalPerson.legalEntityAttachmentDTOs.length) {
            _legalPerson.legalEntityAttachmentDTOs.map(item => {
              if (!item.filePath && item.name) {
                err = true;
              }
            });
          }
          if (err) {
            message.error(messages('enterprise-manage.key338')/*请上传开票二维码图片*/);
          } else {
            let arr = [];
            if (_legalPerson.legalEntityAttachmentDTOs.length) {
              _legalPerson.legalEntityAttachmentDTOs.map(item => {
                if (item.filePath) {
                  arr.push(item);
                }
              });
              _legalPerson.legalEntityAttachmentDTOs = arr;
            }
            if (!this.props.params.legalPersonOID) {
              //创建法人实体
              let legalPerson = Object.assign(_legalPerson, values,
                {
                  i18n: _legalPerson.i18n,
                  companyName: _legalPerson.companyName,
                  accountBank: _legalPerson.accountBank,
                  address: _legalPerson.address,
                  mainLanguage: _legalPerson.mainLanguage,
                });
              this.createLegalPerson(legalPerson)
            } else {
              //更新法人实体
              if (values.setOfBooksId === _legalPerson.setOfBooksName) {
                values.setOfBooksId = _legalPerson.setOfBooksId
              }
              if (values.parentLegalEntityId === _legalPerson.parentLegalEntityName) {
                values.parentLegalEntityId = _legalPerson.parentLegalEntityId
              }
              let legalPerson = Object.assign(_legalPerson, values, {
                i18n: _legalPerson.i18n,
                companyName: _legalPerson.companyName,
                accountBank: _legalPerson.accountBank,
                address: _legalPerson.address,
                mainLanguage: _legalPerson.mainLanguage,
              });
              this.handleUpdate(legalPerson)
            }
          }
        }
      });
    }
  };
  //保存所做的详情修改
  handleUpdate = (legalPerson) => {
    LPService.updateLegalPerson(legalPerson)
      .then((res) => {
        this.isShowPayWarn(res.data, () => {
          this.context.router.goBack();
        });
        this.setState({
          legalPerson: res.data
        })
      })
      .catch((res) => {
      })
  };
  //创建法人实体
  createLegalPerson = (legalPerson) => {
    this.setState({
      loading: true,
    });

    LPService.createLegalPerson(legalPerson)
      .then((res) => {
        this.setState({
          loading: false,
        });
        this.isShowPayWarn(res.data, () => {
          this.context.router.goBack();
        });
      })
      .catch((res) => {
        this.setState({
          loading: false,
        });
      })
  };


  //根据返回结果，显示提示弹窗
  isShowPayWarn = (data, callback) => {
    let alipayRespDTO = data.alipayRespDTO;
    //等于10000，代表成功
    if (alipayRespDTO && alipayRespDTO.code != "10000") {
      if (alipayRespDTO.subMsg || alipayRespDTO.tip) {
        this.setState({
          visibleTips: true,
          payErrTips: alipayRespDTO
        })
      } else {
        callback();
      }
    } else {
      callback();
    }
  };

  //点击取消，返回
  handleCancel = (e) => {
    e.preventDefault();
    this.context.router.goBack();
  };

  handleChange = (e) => {
    if (this.state.loading) {
      this.setState({
        loading: false
      })
    }
  };

  //上传图片后的回调函数
  handleUploadImageChange = (fileList, indexOne) => {
    let legalPerson = this.state.legalPerson;
    let empty = false;
    legalPerson.legalEntityAttachmentDTOs.map((item, index) => {
      if (index === indexOne) {
        item.filePath = fileList.length ? fileList[0].fileURL : "";
        item.attachmentId = fileList.length ? fileList[0].id : "";
      }
    });
    if (fileList.length !== 0) {
      if (legalPerson.legalEntityAttachmentDTOs.length < 5) {
        legalPerson.legalEntityAttachmentDTOs.map(item => {
          if (!item.filePath && !item.name) {
            empty = true;
          }
        });
        !empty && legalPerson.legalEntityAttachmentDTOs.push({
          attachmentId: 10,
          filePath: "",
          name: "",
          i18n: {name: []},
        })
      }
    }
    this.setState({legalPerson})
  };

  //地址：多语言
  i18nAddressChange = (name, i18nName) => {
    const {legalPerson} = this.state;
    legalPerson.address = name;
    legalPerson.i18n.address = i18nName;
  };

  //开户行：多语言
  i18nAccountBankChange = (name, i18nName) => {
    const {legalPerson} = this.state;
    legalPerson.accountBank = name;
    legalPerson.i18n.accountBank = i18nName;
  };

  //法人实体名称：多语言
  i18nCompanyNameChange = (name, i18nName) => {
    const {legalPerson} = this.state;
    legalPerson.companyName = name;
    legalPerson.i18n.entityName = i18nName;
  };

  //渲染语言
  renderLanguageList = (list) => {
    if (list.length > 1) {
      return list.map((item) => <Option value={item.code} key={item.code}>{item.comments}</Option>)
    } else {
      return (
        <Option value="zh_cn" key={1}>
          {messages('enterprise-manage.key99'/*简体中文*/)}
        </Option>
      )
    }
  };

  handleLanguage = (value) => {
    const {legalPerson} = this.state;
    legalPerson.mainLanguage = value;
    legalPerson.mainLanguageName = getLanguageName(value, this.props.languageList);
    //语言
    this.setState({
      legalPerson
    })
  };

  renderParentLegalEntityList = (list) => {
    return list.map((item) => <Option value={item.id} key={item.id}>{item.entityName}</Option>)
  }
  handleParentLegalEntityId = (value) => {
    const {legalPerson} = this.state;
    legalPerson.parentLegalEntityId = value;
    this.setState({
      legalPerson
    })
  };

  //关闭提示
  handleCancelTips = () => {
    this.setState({
      visibleTips: false
    })
  };

  //关闭提示并且返回
  handleCancelTipsBack = () => {
    this.setState({
      visibleTips: false
    }, () => {
      this.context.router.goBack();
    })
  };

  //子应用名称：多语言
  i18nAppNameChange = (name, i18nName, indexOne) => {
    let {legalPerson} = this.state;
    legalPerson.legalEntityAttachmentDTOs.map((item, index) => {
      if (index === indexOne) {
        item.name = name;
        item.i18n.name = i18nName;
      }
    });
    this.setState({legalPerson})
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const {legalPerson, loading, payErrTips} = this.state;
    return (
      <div className="new-legal-person-wrap">
        <Form onSubmit={this.handleSave} onChange={this.handleChange}>
          <Row gutter={24} className="new-lp-row-wrap">
            <Col span={8}>
              <div className="new-lp-row">
                <span className="new-lp-row-re">*</span>
                <span>
                  {/*法人实体名称*/}
                  {messages('enterprise-manage.key103'/*法人实体名称*/)}：
                </span>
              </div>
              <LanguageInput
                key={1}
                name={legalPerson.companyName}
                i18nName={legalPerson.i18n && legalPerson.i18n.entityName ? legalPerson.i18n.entityName : null}
                isEdit={legalPerson.id}
                nameChange={this.i18nCompanyNameChange}
              />
            </Col>
            <Col span={8}>
              <div className="new-lp-row">
                <span className="new-lp-row-re">*</span>
                <span>
                  {/*开户行*/}
                  {messages('enterprise-manage.key104'/*开户行*/)}：
                </span>
              </div>
              <LanguageInput
                key={2}
                name={legalPerson.accountBank}
                i18nName={legalPerson.i18n && legalPerson.i18n.accountBank ? legalPerson.i18n.accountBank : null}
                isEdit={legalPerson.id}
                nameChange={this.i18nAccountBankChange}
              />
            </Col>
            <Col span={8}>
              <div className="new-lp-row">
                <span className="new-lp-row-re">*</span>
                <span>
                  {/*地址*/}
                  {messages('enterprise-manage.key105'/*地址*/)}：
                </span>
              </div>
              <LanguageInput
                key={3}
                name={legalPerson.address}
                i18nName={legalPerson.i18n && legalPerson.i18n.address ? legalPerson.i18n.address : null}
                isEdit={legalPerson.id}
                nameChange={this.i18nAddressChange}
              />
            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key106'/*电话*/)}
                colon={true}>
                {getFieldDecorator('telephone', {
                  initialValue: legalPerson.telephone,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.enter")
                    },
                    {
                      max: 20,
                      message: messages('enterprise-manage.key107'/*不能超过20个字符*/)
                    },
                    {
                      message: messages('enterprise-manage.key108'/*只能是数字与-*/),
                      validator: (rule, value, cb) => {
                        if (value === null || value === undefined || value === "") {
                          cb();
                          return;
                        }
                        var regExp = /^[0-9\- ]+$/i;
                        //去掉空格
                        value = value.replace(/ /g, '');
                        if (value.length <= 20 && regExp.test(value)) {
                          cb();
                        } else {
                          cb(false);
                        }
                      },
                    }
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key109'/*纳税人识别号*/)}
                colon={true}>
                {getFieldDecorator('taxpayerNumber', {
                  initialValue: legalPerson.taxpayerNumber,
                  rules: [
                    {
                      message: messages('enterprise-manage.key350')/*纳税人识别号长度不能超过60*/,
                      validator: (rule, value, cb) => {
                        if (value === null || value === undefined || value === "") {
                          cb();
                          return;
                        }
                        let regExp = /^[a-z0-9_ -]+$/i;
                        //去掉空格
                        value = value.replace(/ /g, '');
                        if (value.length <= 60) {
                          cb();
                        } else {
                          cb(false);
                        }
                      },
                    }
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>
                )
                }
              </FormItem>
            </Col>
            <Col span={8}>
              {/*必须是数字或者减号*/}
              <FormItem
                label={messages('enterprise-manage.key111'/*银行卡号*/)}
                colon={true}>
                {getFieldDecorator('cardNumber', {
                  initialValue: legalPerson.cardNumber,
                  rules: [
                    {required: true, message: messages("common.please.enter")},
                    {
                      message: messages('enterprise-manage.key112'/*必须包含数字*/),
                      validator: (rule, value, cb) => {
                        if (value === null || value === undefined || value === "") {
                          cb();
                          return;
                        }
                        let regExp = /[0-9]/;
                        //去掉空格
                        value = value.replace(/ /g, '');
                        if (value.length <= 30 && regExp.test(value)) {
                          cb();
                        } else {
                          cb(false);
                        }
                      },
                    },
                    {
                      max: 30,
                      message: messages('enterprise-manage.key113'/*不能超过30个字符*/)
                    },
                  ]
                })(
                  <Input placeholder={messages("common.please.enter")}/>)
                }
              </FormItem>

            </Col>
          </Row>
          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key114'/*账套*/)}  /* 账套*/
                colon={true}>
                {getFieldDecorator('setOfBooksId', {
                  initialValue: legalPerson.setOfBooksName,
                  rules: [
                    {
                      required: true,
                      message: messages("common.please.select")
                    },
                  ]
                })(
                  <Selector
                    placeholder={messages("common.please.select")}
                    disabled={legalPerson.setOfBooksId}
                    selectorItem={this.state.sob}/>
                )
                }
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key115'/*上级法人*/)} /* 上级法人*/
                colon={true}>
                {getFieldDecorator('parentLegalEntityId', {
                  initialValue: legalPerson.parentLegalEntityName
                })(
                  <Select
                    showSearch
                    placeholder={messages("common.please.select")}
                    optionFilterProp="children"
                    onChange={this.handleParentLegalEntityId}
                  >
                    {this.renderParentLegalEntityList(this.state.parentLegalEntityList)}
                  </Select>
                )
                }
              </FormItem>
            </Col>
            <Col span={8}>
              {/*状态*/}
              <FormItem
                label={messages("common.status", {status: ""})}
                colon={true}>
                {getFieldDecorator("enable", {
                  initialValue: legalPerson.enable,
                  valuePropName: 'checked',
                })
                (
                  <Switch checkedChildren={<Icon type="check"/>}
                          unCheckedChildren={<Icon type="cross"/>}/>
                )
                }
              </FormItem>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={8}>
              <FormItem
                label={messages('enterprise-manage.key337')/*APP开票信息页显示的语言*/}
                colon={true}>
                {getFieldDecorator('mainLanguage', {
                  initialValue: legalPerson.mainLanguageName
                })(
                  <Select
                    className="select-language"
                    showSearch
                    placeholder={messages("common.please.select")}
                    optionFilterProp="children"
                    onChange={this.handleLanguage}
                    filterOption={(input, option) => {
                      return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                    }}
                  >
                    {this.renderLanguageList(this.props.languageList)}
                  </Select>
                )
                }
              </FormItem>
            </Col>
          </Row>
          <Row style={{color: "rgba(0, 0, 0, 0.85)"}}>
            {messages('enterprise-manage.key116'/*开票二维码*/)}：
            <span style={{
              color: "rgba(0,0,0,0.5)",
              fontSize: 13
            }}>{messages('enterprise-manage.key339')/*建议上传图片尺寸大于400px * 400px，大小不超过2M*/}</span>
          </Row>
          <Row style={{marginBottom: 32}}>
            {
              legalPerson.legalEntityAttachmentDTOs && legalPerson.legalEntityAttachmentDTOs.length ?
                legalPerson.legalEntityAttachmentDTOs.map((item, index) => {
                  return (
                    <Col span={4} style={{marginRight: 20}} key={index}>
                      <div style={{margin: "20px 50px 10px"}}>
                        <ImageUpload attachmentType="INVOICE_IMAGES"
                                     uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                                     fileType={["PNG", 'png', 'jpeg', 'jpeg', 'jpg', 'JPG', 'bmp', 'BMP']}
                                     defaultFileList={item.filePath ? [{
                                       fileURL: item.filePath,
                                       attachmentOID: item.attachmentId,
                                       fileName: item.name,
                                     }] : []}
                                     onChange={(fileList) => this.handleUploadImageChange(fileList, index)}
                                     maxNum={1}/>
                      </div>
                      <div style={{width: 200}}>
                        <LanguageInput
                          key={item.attachmentId}
                          isEdit={item.name}
                          name={item.name}
                          i18nName={item.i18n && item.i18n.name ? item.i18n.name : null}
                          placeholder={messages('enterprise-manage.key340')/*请输入票台名称*/}
                          nameChange={(name, i18nName) => this.i18nAppNameChange(name, i18nName, index)}/>
                      </div>
                    </Col>
                  )
                })
                : null
            }
          </Row>
          <div>
            <Button type="primary" loading={loading}
                    htmlType="submit">
              {messages("common.save") /*保存*/}
            </Button>
            <Button onClick={this.handleCancel}
                    style={{marginLeft: 8}}>
              {messages("common.cancel") /*取消*/}
            </Button>
          </div>
        </Form>


        <Modal
          width={500}
          title={null}
          destroyOnClose={true}
          visible={this.state.visibleTips}
          footer={null}
          onCancel={this.handleCancelTips}
        >
          <h3>
            <Icon type="exclamation-circle" style={{color: "#faad14"}}/>
            &nbsp;&nbsp;&nbsp;
            {payErrTips.subMsg}
          </h3>
          <div>
            {payErrTips.tip}
          </div>

          <div style={{textAlign: "right", marginTop: 10}}>
            <Button type="primary" onClick={this.handleCancelTipsBack}>
              {messages("common.ok") /*确定*/}
            </Button>
          </div>
        </Modal>

      </div>
    )
  }
}


NewLegalPerson.contextTypes = {
  router: React.PropTypes.object
};


function mapStateToProps(state) {
  return {
    languageList: state.login.languageList,
    language: state.main.language,
    authToken: state.main.authToken,
    user: state.login.user
  }
}

const WrappedNewLegalPerson = Form.create()(NewLegalPerson);

export default connect(mapStateToProps)(WrappedNewLegalPerson);
